/*
    Copyright 2013 Jonathan Kaschak

    This file is part of TerraTamper.

    TerraTamper is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    TerraTamper is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with TerraTamper.  If not, see <http://www.gnu.org/licenses/>.
*/

package Main;

import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main
{
  private static ServerSocket Server;
  private static Socket incoming;
  private static Socket outgoing;
  private static String localhost;
  private static int localport;
  private static String remotehost;
  private static int remoteport;
  
  public static ProxyConnection localhost_socket;

  private static boolean argParams(String[] args)
  {
    if (args.length == 0) return false; try
    {
      localhost = args[0];
      localport = Integer.parseInt(args[1]);
      remotehost = args[2];
      remoteport = Integer.parseInt(args[3]);
      return true;
    } catch (Exception e) {
      System.out.println("usage: ./terratamper.jar <localhost> <localport> <remotehost> <remoteport>\n");
    }
    return false;
  }

  private static void askParams() {
    try {
      Scanner user_input = new Scanner(System.in);

      System.out.println("Enter server ip address:");
      remotehost = user_input.next();
      System.out.println("Enter server port:");
      remoteport = Integer.parseInt(user_input.next());
      System.out.print("\n");
    } catch (Exception e) {
      askParams();
    }
  }

  public static void main(String[] args) {
    //https://docs.google.com/spreadsheet/ccc?key=0AqGJGhuHJlhrdDNfcWVwUkhjcUFrLTI1eS01cG1fR0E&hl=en_US#gid=26
    System.out.println("         _____                   _____                                         \n" +
                       "        |_   _|___ _ __ _ __ __ |_   _|__ _ _ __ ___  _ __   ___ _ __          \n" +
                       "          | | / _ \\  __|  __/ _  || | / _  |  _   _ \\|  _ \\ / _ \\  __|         \n" +
                       "          | ||  __/ |  | | | (_| || || (_| | | | | | | |_) |  __/ |            \n" +
                       "          |_| \\___|_|  |_|  \\__ _||_| \\__ _|_| |_| |_|  __/ \\___|_|            \n" +
                       "                                                     |_|                       \n" +
                       "                TerraTamper Version: 0.1 (For Terraria 1.2.1.2)                \n" +
                       "                          terratamper.googlecode.com                           \n" +
                       "                                                                               \n" +
                       "TerraTamper is a packet modifying proxy, so it must be use in addition to a    \n" +
                       "server. Users will connect to TerraTamper like they would to a server, then    \n" +
                       "TerraTamper will continue the user's connection to the server.                 \n");
    localhost = "127.0.0.1";
    localport = 7778;
    remotehost = "127.0.0.1";
    remoteport = 7777;
    if (!argParams(args)) askParams(); try {
        Server = new ServerSocket(localport, 1000, InetAddress.getByName(localhost));
    } catch (IOException ex) {
        System.out.println("Error creating server socket. Is TerraTamper already running?");
        System.exit(0);
    }
    System.out.println("Now connect Terraria to TerraTamper: " + localhost + " port " + localport + "\n");
    while (true) try {
        incoming = Server.accept();
        /*InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9070); 
        java.net.Proxy javaProxy = new Proxy(Proxy.Type.SOCKS, address);
        Socket server = new Socket(javaProxy);*/
        outgoing = new Socket(remotehost, remoteport);
        ProxyConnection thread1 = new ProxyConnection(incoming, outgoing, true);
        ProxyConnection thread2 = new ProxyConnection(outgoing, incoming, false);
        if(incoming.getInetAddress().isLoopbackAddress()){
            thread1.localhost = true;
            thread2.localhost = true;
            localhost_socket = thread1;
        }
        thread1.othergoing = thread2;
        thread2.othergoing = thread1;
        thread1.start();
        thread2.start();
    } catch (UnknownHostException ex) {
        System.out.println("Error connecting to server: Unknown Host");
    } catch (IOException ex) {
        System.out.println("Error connecting to server: " + remotehost + " port " + remoteport 
                + ". Restart TerraTamper and make sure you enter the right server ip!");
    }
  }
}
